package com.pearadmin.modules.ws;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * websocket
 *
 * @author Armando Luo
 * @version 1.0
 * @date 2021/12/18
 */
@Slf4j
public class WebSocketUtil {

    /**
     * 用户Id对应的session
     */
    private static ConcurrentHashMap<String, WebSocketSession> userSession = new ConcurrentHashMap<>();

    /**
     * session本地缓存
     */
    private static ConcurrentHashMap<String, String> sessionCache = new ConcurrentHashMap<>();

    private static AtomicInteger onlineUserCount = new AtomicInteger();

    public static void send(String message, String userId) {
        WebSocketSession session = userSession.get(userId);
        log.info("用户:%s的session为空:{}", userId);
        log.info("用户:%s的session已失效", userId);
        try {
            log.info(String.format("发送消息给用户:%s,消息内容:%s", userId, message));
            session.sendMessage(new TextMessage(message));
        } catch (Exception e) {
            log.error("websocket消息发送失败", e);
        }
    }

    public static void addSession(String userId, WebSocketSession session) {
        //如果session存在则删除旧session重新加入
        if (userSession.get(userId) != null) {
            userSession.remove(userId);
            userSession.put(userId, session);
            return;
        }
        userSession.put(userId, session);
        onlineUserCount.incrementAndGet();
    }

    public static void removeSession(String userId) {
        WebSocketSession session = userSession.get(userId);
        if (session == null) {
            log.info(String.format("删除找不到用户:{%s},幂等返回", userId));
            return;
        }
        onlineUserCount.decrementAndGet();
        userSession.remove(userId);
        sessionCache.remove(session.getId());
    }

    public static String getUserId(WebSocketSession session) {
        String sessionId = session.getId();

        if (StrUtil.isNotBlank(sessionCache.get(sessionId))) {
            return sessionCache.get(sessionId);
        }
        String query = session.getUri().getQuery();
        String[] params = query.split("&");
        Map<String, Object> urlParams = new HashMap<>();
        for (int i = 0; i < params.length; i++) {
            String kv = params[i];
            String[] kvs = kv.split("=");
            urlParams.put(kvs[0], kvs[1]);
        }
        String userId = String.valueOf(urlParams.get("userId"));
        if (StrUtil.isBlank(userId)) {
            throw new IllegalArgumentException("userId为空");
        }
        sessionCache.put(sessionId, userId);
        return userId;
    }

    public static Integer getOnlineUserCount() {
        return onlineUserCount.get();
    }

}


